<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/8/15 0015
 * Time: 14:39
 */

namespace common\models\Percentage;


use common\models\Plug\Plug;
use common\models\PlugsRunTotal\PlugsRunTotal;
use yii\helpers\ArrayHelper;

class Percentage extends PercentageBase
{
    public static function set($date, $plugId, $upperTerminal = 0)
    {
        if ( !strtotime($date) ) {
            self::error("无效的时间");
            return false;
        }
        if ( !$plugId ) {
            self::error("无效的插件");
            return false;
        }
        //获取插件数据
        $plugsRunTotal = PlugsRunTotal::find()->where([
            "plug_id" => $plugId,
            "created_date" => $date
        ])->select("sum(terminal_num) as terminal_num")->asArray()->one();

        $query = self::findOne([
            "plug_id" => $plugId,
            "created_date" => $date
        ]);
        if ( !$query ) {
            $query = new self();
            $query->plug_id = $plugId;
            $query->created_date = $date;
            $query->status = self::STATUS_NO;
        } else {
            if ( $query->status == self::STATUS_YES ) {
                return $query;
            }
        }
        $query->upper_num = $upperTerminal;
        $query->real_num = $plugsRunTotal["terminal_num"];
        if ( !$query->upper_num ) {
            $query->upper_num = $query->real_num;
        }
        if ( $query->save() ) {
            return $query;
        }
        self::error($query->getFirstErrorToStr());
        return false;
    }

    public function getNumRate()
    {
        return $this->upper_num / $this->real_num;
    }

    public function getPlug()
    {
        return $this->hasOne(Plug::class, [
            "id" => "plug_id"
        ]);
    }

    public static function getStatusMap($key = "ALL", $default = false)
    {
        $ret = [
            self::STATUS_YES => "已完成",
            self::STATUS_NO => "待完成"
        ];

        if ( $key === "ALL" ) {
            return $ret;
        }
        return ArrayHelper::getValue($ret, $key, $default);
    }
}